<template>
  <div class="content flex column gap10">

    <div class="status flex aic" @click.native="changeTaskType">
      <div class="status-item" :class="{ check: 'uri' == form.type }" data-type="uri">链接任务</div>
      <div class="status-item" :class="{ check: 'torrent' == form.type }" data-type="torrent">种子任务</div>
    </div>
    <div class="addTask p20">
      <el-form ref="taskFormRef" :model="form" :rules="rules" status-icon>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="" prop="uris" v-if="'uri' == form.type">
              <el-input v-model="form.uris" type="textarea" auto-complete="off" :autosize="{ minRows: 3, maxRows: 5 }"
                placeholder="添加多个下载链接时，请确保每行只有一个链接（支持磁力链）" @paste.native="handleUriPaste" />
            </el-form-item>
            <el-form-item label="" prop="torrent" v-if="'torrent' == form.type">
              <SelectTorrent @change="handleTorrentChange"></SelectTorrent>
            </el-form-item>
          </el-col>

          <el-col :span="15" :xs="24">
            <el-form-item label="重命名" :label-width="labelWidth">
              <el-input placeholder="选填" v-model="form.out">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="9" :xs="24">
            <el-form-item label="分片数" :label-width="labelWidth">
              <el-input-number v-model="form.split" controls-position="right" :min="1" :max="128" label="分片数">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="存储路径" :label-width="labelWidth">
          <el-input placeholder="" v-model="form.dir">
            <template #prepend>
              <history-directory slot="prepend" @selected="handleHistoryDirectorySelected" />
            </template>
            <template #append>
              <select-directory @selected="handleNativeDirectorySelected" />
            </template>

          </el-input>
        </el-form-item>

        <div class="task-advanced-options" v-if="showAdvanced">
          <el-form-item label="User-Agent" :label-width="labelWidth">
            <el-input type="textarea" auto-complete="off" :autosize="{ minRows: 2, maxRows: 3 }"
              placeholder="User-Agent:" v-model="form.userAgent">
            </el-input>
          </el-form-item>

          <el-form-item label="Authorization" :label-width="labelWidth">
            <el-input type="textarea" auto-complete="off" :autosize="{ minRows: 2, maxRows: 3 }"
              placeholder="Authorization" v-model="form.authorization">
            </el-input>
          </el-form-item>

          <el-form-item label="Referer" :label-width="labelWidth">
            <el-input type="textarea" auto-complete="off" :autosize="{ minRows: 2, maxRows: 3 }" placeholder="Referer"
              v-model="form.referer">
            </el-input>
          </el-form-item>

          <el-form-item label="cookie" :label-width="labelWidth">
            <el-input type="textarea" auto-complete="off" :autosize="{ minRows: 2, maxRows: 3 }" placeholder="cookie"
              v-model="form.cookie">
            </el-input>
          </el-form-item>
          <el-row :gutter="12">
            <el-col :span="16" :xs="24">
              <el-form-item label="代理" :label-width="labelWidth">
                <el-input type="text" auto-complete="off" placeholder="[http://][USER:PASSWORD@]HOST[:PORT]"
                  v-model="form.allProxy">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <div class="help-link">
                <a target="_blank" href="https://github.com/agalwood/Motrix/wiki/Proxy" rel="noopener noreferrer">
                  代理配置说明
                </a>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <el-row>
        <el-col :span="9" :xs="9">
          <el-checkbox class="chk" v-model="showAdvanced">
            高级选项
          </el-checkbox>
        </el-col>
        <el-col :span="15" :xs="15">
          <el-button @click="handleCancel()">
            取消
          </el-button>
          <el-button type="primary" @click="submitForm()">
            确认
          </el-button>
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script setup>
import { useConfigStore } from "@/store/configStore.js"
import { useTaskStore } from "@/store/taskStore.js"

import { nextTick, ref } from 'vue'
import { ElMessage } from 'element-plus'
import HistoryDirectory from "@/components/historyDirectory/index.vue"
import SelectDirectory from "@/components/selectDirectory/index.vue"
import SelectTorrent from "@/components/selectTorrent/index.vue"
import { ipcApiRoute } from "@/api/main.js"
import { ipc } from "@/utils/ipcRenderer.js"
import {
  buildUriPayload,
  buildTorrentPayload
} from '@/utils/task.js'

import { useRouter } from "vue-router"
const router = useRouter();


const configStore = useConfigStore()
const taskStore = useTaskStore()

const labelWidth = ref("110px")
const taskFormRef = ref()
const form = ref({
  uris: '',
  torrent: '',
  out: "",
  split: 64,
  dir: '',
  userAgent: '',
  authorization: '',
  Referer: '',
  Cookie: '',
  allProxy: '',
  type: 'uri'
})
const rules = ref({
  uris: [{ required: true, message: '请输入下载地址', trigger: 'blur' },],
  torrent: [{ required: true, message: '请上传种子文件', trigger: 'blur' },],
  dir: [{ required: true, message: '请输入存储路径', trigger: 'blur' },],
})
const changeTaskType = (e) => {
  form.value.type = e.target.dataset.type
}
const showAdvanced = ref(false)

const handleUriPaste = (e) => {
  // console.log(e)
  nextTick(() => {
    const uris = form.value.uris
    detectThunderResource(uris)
  })
}




const detectThunderResource = (uris) => {
  // console.log("detectThunderResource")
  if (uris.includes('thunder://')) {
    ElMessage({
      message: '友情提示：迅雷链接解码之后的资源不一定存在。',
      type: 'warning',
      duration: 6000
    })
  }
}

const handleTorrentChange = (value) => {
  let { torrent, selectedFileIndex } = value;
  console.log(form.value, value)
  form.value.torrent = torrent
  form.value.selectFile = selectedFileIndex

}

// 打开历史
const handleHistoryDirectorySelected = (res) => {

}

// 选择本地文件夹
const handleNativeDirectorySelected = (res) => {
  form.value.dir = res
}


const handleCancel = () => {
  // taskFormRef.value.validate(valid => {
  //   // 提交数据
  //   console.log(valid)
  // })
  router.replace({
    path: '/down'
  })
}

const submitForm = () => {
  taskFormRef.value.validate(valid => {
    if (valid) {
      // 添加任务
      let api = ipcApiRoute.addTaskUri;
      let formVal = {}
      if (form.value.type == 'torrent') {
        api = ipcApiRoute.addTorrent;
        formVal = buildTorrentPayload(form.value)
      } else {
        formVal = buildUriPayload(form.value)
      }
      console.log('formVal', formVal)
      ipc.invoke(api, formVal).then(res => {
        // 返回值
        console.log(res)
        // 定时下载任务

        taskStore.getActiveTaskInfoInterval({
          type: "active",
          offset: 0,
          num: 20,
        })

        // 跳转页面
        router.replace({
          path: '/down'
        })
      })
    }
  })


}
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0px;
}

:deep(.group__prepend) {
  padding: 0px;
}


.status {
  width: fit-content;
  // height: 100%;
  border-radius: 16px;
  @include background_color("bg_menu_base2");
  @include font_color("font_base_in");
  font-size: 14px;
  // padding: 5px 20px;
  box-sizing: border-box;
  overflow: hidden;
  transition: all 0.3s;

  &-item {
    width: fit-content;
    height: 40px;
    line-height: 40px;
    cursor: pointer;
    padding: 0px 10px
  }

  .check {
    // width: 80%;
    text-align: center;
    @include background_color("bg_menu_base");
    // border-radius: 10px;
    border-radius: 16px;
  }
}

.addTask {
  border-radius: 16px;
  border: 1px solid;
  @include border_color("down_list_item_border2");
}
</style>